package com.orgname.glvone.glvtwo.common.util;

import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

public class DistributedLock {

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取分布式锁，默认锁60秒
     *
     * @param key lock key
     * @return
     */
    public boolean tryLock(String key) {
        return tryLock(key, 60);
    }

    /**
     * 获取分布式锁
     *
     * @param key        lock key
     * @param expiryTime 超时时间
     * @return
     */
    public boolean tryLock(String key, long expiryTime) {
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(key, 1, expiryTime, TimeUnit.SECONDS));
    }

    /**
     * 释放锁
     *
     * @param key
     */
    public void releaseLock(String key) {
        redisTemplate.delete(key);
    }

}
